package core

import (
	"context"

	"github.com/go-kratos/kratos/v2/errors"

	"gitee.com/danqingzhao/go-dango/pkg/proto/auth"
	"gitee.com/danqingzhao/go-dango/pkg/proto/settings"
)

type ContextKey string

const (
	HostKey          ContextKey = "Host"
	XForwardedForKey ContextKey = "XForwardedFor"
	UserAgentKey     ContextKey = "UserAgent"
	AuthorizationKey ContextKey = "Authorization"
	UserClaimsKey    ContextKey = "UserClaims"
)

func ContextMissing(tmpData map[string]string) *errors.Error {
	return errors.BadRequest(
		settings.ErrorReason_CONTEXT_MISSING.String(),
		"context lacks necessary fields",
	).WithMetadata(tmpData)
}

func GetHost(ctx context.Context) (string, *errors.Error) {
	host, ok := ctx.Value(HostKey).(string)
	if !ok || host == "" {
		tmpData := map[string]string{"key": string(HostKey)}
		return "", ContextMissing(tmpData)
	}
	return host, nil
}

func GetXForwardedFor(ctx context.Context) (string, *errors.Error) {
	ip, ok := ctx.Value(XForwardedForKey).(string)
	if !ok || ip == "" {
		tmpData := map[string]string{"key": string(XForwardedForKey)}
		return "", ContextMissing(tmpData)
	}
	return ip, nil
}

func GetUserAgent(ctx context.Context) (string, *errors.Error) {
	ua, ok := ctx.Value(UserAgentKey).(string)
	if !ok || ua == "" {
		tmpData := map[string]string{"key": string(UserAgentKey)}
		return "", ContextMissing(tmpData)
	}
	return ua, nil
}

func GetAuthorization(ctx context.Context) (string, *errors.Error) {
	auth, ok := ctx.Value(AuthorizationKey).(string)
	if !ok || auth == "" {
		tmpData := map[string]string{"key": string(AuthorizationKey)}
		return "", ContextMissing(tmpData)
	}
	return auth, nil
}

func GetUserClaims(ctx context.Context) (*auth.UserClaims, *errors.Error) {
	uc, ok := ctx.Value(UserClaimsKey).(*auth.UserClaims)
	if !ok || uc == nil {
		tmpData := map[string]string{"key": string(UserClaimsKey)}
		return nil, ContextMissing(tmpData)
	}
	return uc, nil
}
